<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : Payment.php
 * Created on : 2022-4-6 12:10:52
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\models;

use think\Model;

/**
 * 
 * Class Payment
 * Tiger <1192851302@qq.com> 2022-4-6 12:10:52
 */
class Payment extends Model {

    /**
     * 生成支付
     * @author Tiger <1192851302@qq.com>
     * @param type $type
     * @param type $out_trade_no
     * @param type $money
     * @param type $join_id
     * @param type $body
     * @param type $callback
     * @param type $mid
     * @param type $addons
     * @return type
     */
    public static function Generate($type, $out_trade_no, $money, $join_id, $body, $callback = null, $attach = null, $mid = 0, $addons = null) {
        $uid = request()->uid();
        if (empty($mid)) {
            $mid = request()->mid();
        }
        return self::create(compact('uid', 'mid', 'type', 'out_trade_no', 'money', 'join_id', 'body', 'callback', 'addons', 'attach'));
    }

    /**
     * 发起支付
     * @author Tiger <1192851302@qq.com>
     * @param type $id
     * @return type
     * @throws \think\Exception
     */
    public static function pay($id) {
        $data = self::where('id', $id)->field(['id', 'status', 'body', 'out_trade_no', 'money', 'attach'])->find();
        if (empty($data)) {
            throw new \think\Exception('订单号不存在');
        }
        if (1 <= $data['status']) {
            throw new \think\Exception('已经支付过了');
        }
        return call_user_func_array(array(str_ireplace("{platform}", $data['attach'], "\app\chicken\service\{platform}"), "bridgeConfig"), [$data['body'], $data['out_trade_no'], $data['money'], $data['attach']]);
    }

    /**
     * 支付查询
     * @author Tiger <1192851302@qq.com>
     * @param type $id
     * @return int 
     * @throws \think\Exception
     */
    public static function query($id) {
        $data = self::where('id', $id)->field(['id', 'status'])->find();
        if ($data === null) {
            throw new \think\Exception('订单号不存在');
        }
        return $data['status'];
    }

}
